﻿function MessageBoard(id, text)
{
	this.id = id;
	this.text = text;
}
{
	// instance methods

	// database

	MessageBoard.prototype.readFromDatabase = function
	(
		database, 
		id, 
		objectForEventLoaded, 
		eventLoaded
	)
	{
		var queryText = 
			"select * from " 
			+ this.entityName();

		database.query
		(
			queryText,
			this,
			objectForEventLoaded,
			eventLoaded,
			null // eventFinished
		);
	}

	MessageBoard.prototype.readFromDatabase_BuildFromRow = function
	(
		row,
		objectForEventLoaded, 
		eventLoaded
	)
	{
		this.id = row.ID;
		this.text = row.Text;

		eventLoaded.call(objectForEventLoaded, this);
	}

	MessageBoard.prototype.writeToDatabase = function
	(
		database, 
		objectForEvents, 
		eventFinished
	)
	{
		var queryText;

		if (this.persistenceStatus == PersistenceStatus.Instances.Saved)
		{
			// do nothing
		}
		else if (this.persistenceStatus == PersistenceStatus.Instances.Created)
		{
			queryText = 
				"insert into "
				+ this.entityName()
				+ " select " 
				+ this.id + ","
				+ "'" + this.text + "'";			

			database.query
			(
				queryText,
				this,
				objectForEvents,
				null, //eventLoaded
				eventFinished
			);
		}
		else if (this.persistenceStatus == PersistenceStatus.Instances.Modified)
		{
			queryText = 
				"update "
				+ this.entityName()
				+ " set " 
				+ " text = '" + this.text + "'";

			database.query
			(
				queryText,
				this,
				objectForEvents,
				null, // eventLoaded
				eventFinished
			);
		}
	}

	// entity

	MessageBoard.EntityName = "MessageBoard";
	MessageBoard.prototype.entityName = function() { return MessageBoard.EntityName; }

	// XML

	MessageBoard.fromXMLElement = function(xmlElement)
	{
		var returnValue = new MessageBoard
		(			
			xmlElement.attributes["ID"].value,
			xmlElement.attributes["Text"].value
		);

		return returnValue;
	}

	MessageBoard.prototype.toXMLElement = function()
	{
		var returnValue = new XMLElement
		(
			null, // parent
			this.entityName(),
			[ 
				new XMLAttribute("ID", this.id),
				new XMLAttribute("Text", this.text), 
			],
			[] // children
		);

		return returnValue;	
	}
}